dojo.provide("dojot.group2.security");

(function(){
	var baseAccess = [];
		if(tjConfig.isAdmin){
			baseAccess.push("admin");
		}
		if(tjConfig.isGroupMember){
			baseAccess.push("groupMember");
		}
		if(tjConfig.isOwner){
			baseAccess.push("owner");
		}
		if(tjConfig.isMaskMember){
			baseAccess.push("maskMember");
		}
	var isAccess = function(tjConfig,area){
		
		//因为有些小资源有自己独立的ownerId,所以需要额外进行判断
		var dealWithItem = function(item){
			var isHaveAccess = false;
			var access;
			var ownerId = dojo.attr(item,"ownerId");
			//如果是子资源的话，而且不是当前大资源的owner的话,需要进行重新设置owner属性
			if(ownerId && (ownerId == tjConfig.viewId)){
				access = dojo.clone(baseAccess);
				access.push("owner");
			}
						//判断
			if(tjConfig.isMaskMember){
				access = [];
			}
			isHaveControlAndShow(item,(access || baseAccess));
		}
		var blockTag = ['div','li','p'];
		var showItem = function(item){
			var tagName = item.tagName.toLowerCase();
			if(tagName && (dojo.indexOf(blockTag,tagName) > -1)){
				dojo.style(item,"display","block");
				return;
			}
			dojo.style(item,"display","inline");
		}
		//根据给的权限来控制是否显示操作元素
		var isHaveControlAndShow = function(item,access){
			var controls = item.className.split(/ +/g);
			var isHave = dojo.some(controls,function(control){
				if(dojo.indexOf(access,control) > -1){
					showItem(item);
					return true;
				}
			});
		}
		if(dojo.indexOf(baseAccess,"owner") == -1){
			dojo.query(".control",area).forEach(dealWithItem);
		}else{
			dojo.query(".control",area).forEach(showItem);
		}	
	};
	isAccess = dojo.partial(isAccess, tjConfig);
	var isHaveAccess = function(tjConfig,controls,ownerId){
			//如果是子资源的话，而且不是当前大资源的owner的话,需要进行重新设置owner属性
			var access;
			if(ownerId && (ownerId == tjConfig.viewId)){
				access = dojo.clone(baseAccess);
				access.push("owner");
			}
			
			access = access || baseAccess
			var isHave = dojo.some(controls,function(control){
				if(dojo.indexOf(access,control) > -1){
					return true;
				}
			});
			return isHave;
	}
	isHaveAccess = dojo.partial(isHaveAccess, tjConfig);
	dojot.security = {
		isAccess: isAccess,
		isHaveAccess: isHaveAccess,
		getBaseAccess:function(){
			return dojo.clone(baseAccess);
		},
		isBaseOwner:function(){
			return tjConfig.isOwner;
		},
		isBaseAdmin: function(){
			return tjConfig.isAdmin;
		},
		isBaseOwnerOrIsAdmin:function(){
			return tjConfig.isAdmin || tjConfig.isOwner
		},
		isBaseOwnerAndIsAdmin:function(){
			return tjConfig.isAdmin && tjConfig.isOwner
		},
		isBaseOwnerOrIsAdminOrOwner:function(ownerId){
			return tjConfig.isAdmin || tjConfig.isOwner || (tjConfig.viewId === ownerId);
		}
	}
}());